<template>
  <div class="user-info-form asset-info-form">
    <el-form
      v-loading="loading"
      label-width="150px"
      :model="appVInfoForm"
      :rules="appVInfoFormRules"
      ref="appVInfoForm"
      @submit.native.prevent
    >
      <el-form-item label="所属平台：" prop="organizationId">
        <tree-select
          v-model="appVInfoForm.organizationId"
          filterable
          clearable
          :width="386"
          :data="ucPlatList"
          :defaultProps="buildDefaultProps"
          :checkedKeys="defaultCheckedBuildId"
          :nodeKey="buildNodeKey"
        ></tree-select>
      </el-form-item>
      <el-form-item label="类型：" prop="type">
        <el-select v-model="appVInfoForm.type" @change="selectType">
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="版本名称：" prop="softName">
        <el-input v-model="appVInfoForm.softName" clearable></el-input>
      </el-form-item>
      <el-form-item label="版本号：" prop="softNumber">
        <el-input v-model="appVInfoForm.softNumber" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否强制更新：" prop="isManupdate">
        <el-select v-model="appVInfoForm.isManupdate">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="更新内容：" prop="content">
        <el-input v-model="appVInfoForm.content" clearable></el-input>
      </el-form-item>
      <template v-if="fileInput">
        <!-- <el-form-item label="安装包名称："  prop='packgeName'>
          <el-input
            v-model="appVInfoForm.packgeName"
            clearable>
          </el-input>
        </el-form-item>-->
        <el-form-item label="上传文件：" prop="files">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="false"
            ref="upload"
            :data="qiniuData"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemovePic"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
            :on-preview="$imgPreview"
            :file-list="qiniuData.fileList"
            :limit="1"
            :on-exceed="handleExceed"
            accept="application/*"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-input style="display:none;" v-model="appVInfoForm.files"></el-input>
        </el-form-item>
      </template>
      <el-form-item label="安装包大小（M）：" prop="size">
        <el-input v-model="appVInfoForm.size" clearable></el-input>
      </el-form-item>
      <el-form-item label="安装包路径：" prop="url">
        <el-input v-model="appVInfoForm.url" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注：" prop="remarks">
        <el-input v-model="appVInfoForm.remarks" clearable></el-input>
      </el-form-item>
      <el-form-item label-width="0" class="verifyidentity-button">
        <el-button @click.stop="closeFun(false)" round>取消</el-button>
        <el-button type="primary" @click="saveGridInfo('appVInfoForm')" round>保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { qnToken } from '@/api/api'
import util from '@/utils/util'
import { updateAppV } from '@/api/sysConfig'
import TreeSelect from '@/libs/TreeSelect/Main'
export default {
  name: 'appVInfo',
  // 引入子组件
  components: {
    TreeSelect,
  },
  props: {
    platVersionInfo: {
      type: Object,
    },
    ucOrgList: {
      type: Array,
    },
    closeFun: {
      type: Function,
      required: true,
    },
  },
  data() {
    return {
      loading: false,
      fileInput: false,
      ucPlatList: this.ucOrgList,
      qiniuData: {
        //上传图片携带的参数
        token: '',
        key: '',
        fileList: [],
      },
      typeList: [
        { id: 1, name: 'ios' },
        { id: 2, name: 'android' },
        { id: 3, name: '视频客户端' },
        { id: 4, name: '平台客户端' },
        { id: 5, name: 'h5' },
        { id: 50, name: '思维h5' },
        { id: 7, name: '平台前端' },
      ],
      buildDefaultProps: {
        children: 'nodes',
        label: 'name',
        value: 'id',
      },
      buildNodeKey: 'id',
      defaultCheckedBuildId: [],
      // 表单数据
      appVInfoForm: {
        organizationId: 0,
        type: 1,
        softName: '',
        softNumber: '',
        isManupdate: '',
        //packgeName: '',
        content: '',
        size: '',
        url: '',
        remarks: '',
        files: '',
      },
      // 表单校验
      appVInfoFormRules: {
        // organizationId: [
        //   { required: true, message: '请选择联网单位', trigger: 'change' }
        // ],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        softName: [
          { required: true, message: '请输入版本名称', trigger: 'change' },
        ],
        softNumber: [
          { required: true, message: '请输入版本号', trigger: 'change' },
          {
            pattern: /^[0-9]*[1-9][0-9]*$/,
            message: '版本号必须为整数',
            trigger: 'blur',
          },
        ],
        isManupdate: [
          { required: true, message: '请选择是否强制更新', trigger: 'change' },
        ],
        /*packgeName: [
            { required: true, message: '请输入安装包名称', trigger: 'change' }
          ],*/
        files: [{ required: true, message: '请上传文件', trigger: 'change' }],
        content: [
          { required: true, message: '请输入更新内容', trigger: 'change' },
        ],
        size: [{ required: true, message: ' ', trigger: 'blur' }],
        url: [{ required: true, message: ' ', trigger: 'blur' }],
        remarks: [{ required: true, message: '请输入备注', trigger: 'change' }],
      },
    }
  },
  created() {
    let that = this
    that.getToken()
    // 如果有历史值，设置回显
    if (that.platVersionInfo.id) {
      that.appVInfoForm.id = that.platVersionInfo.id
      that.appVInfoForm.organizationId = that.platVersionInfo.organizationId
      that.appVInfoForm.type = that.platVersionInfo.type
      that.appVInfoForm.softName = that.platVersionInfo.softName
      that.appVInfoForm.softNumber = that.platVersionInfo.softNumber
      that.appVInfoForm.isManupdate = that.platVersionInfo.isManupdate + ''
      that.appVInfoForm.content = that.platVersionInfo.content
      that.appVInfoForm.size = that.platVersionInfo.size
      that.appVInfoForm.url = that.platVersionInfo.url
      that.appVInfoForm.remarks = that.platVersionInfo.remarks
      that.appVInfoForm.files = 0
      that.selectType(that.platVersionInfo.type)
    }
    if (that.platVersionInfo.organizationId) {
      that.defaultCheckedBuildId = that.platVersionInfo.organizationId
        .toString()
        .split(',')
    } else {
      that.defaultCheckedBuildId = ['0']
    }
    // 设置上传文件初始值
    that.platVersionInfo.url
      ? $.each(that.platVersionInfo.url.split(','), (index, url) => {
          that.qiniuData.fileList.push({
            name: that.platVersionInfo.url,
            url: url,
          })
        })
      : ''
  },
  methods: {
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token = result.data
      })
    },
    beforeAvatarUpload: function (file) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      //this.qiniuData.key = file.name;
      const isApk = file.type === 'application/vnd.android.package-archive'
      const isExe = file.type === 'application/x-msdownload'
      const isZip =
        file.type === 'application/x-zip-compressed' ||
        file.type === 'application/zip' // 兼容苹果处理
      const isLt500M = file.size / 1024 / 1024 < 500
      if (!isApk && !isExe && !isZip) {
        this.$message.error('文件只能是 apk/exe/zip 格式!')
        return false
      }
      if (!isLt500M) {
        this.$message.error('文件大小不能超过 500MB!')
        return false
      }
    },
    handleAvatarSuccess: function (res, file, fileList) {
      //上传成功
      this.qiniuData.fileList = fileList
      this.appVInfoForm.url = QINIUUPLOADURL.indexOf('uploadFile')>-1? res.data:QINIUPATH+res.key
      this.appVInfoForm.size = (file.size / 1024 / 1024).toFixed(2)
      this.appVInfoForm.files = 0
    },
    handleRemovePic: function (file, fileList) {
      //删除成功
      this.qiniuData.fileList = fileList
      this.appVInfoForm.url = ''
      this.appVInfoForm.size = ''
      this.appVInfoForm.files = ''
    },
    handleError: function (res) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
      this.appVInfoForm.files = ''
    },
    handleExceed(files, fileList) {
      //文件超出个数限制时的钩子
      this.$message.warning(`只能上传个文件！`)
    },
    // 保存
    saveGridInfo(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      let type = 1
      let parames = {}
      // 校验表单
      that.$refs[formName].validate((valid) => {
        if (valid) {
          var parames = {
            content: that.appVInfoForm.content,
            isManupdate: that.appVInfoForm.isManupdate,
            remarks: that.appVInfoForm.remarks,
            organizationId: that.appVInfoForm.organizationId,
            size: that.appVInfoForm.size,
            softName: that.appVInfoForm.softName,
            softNumber: that.appVInfoForm.softNumber,
            type: that.appVInfoForm.type,
            url: that.appVInfoForm.url,
            id: that.platVersionInfo.id,
          }

          if (parames.id == null || parames.id == '') {
            parames.id = 0
          }
          // 调用保存接口
          updateAppV(parames).then((res) => {
            if (res.status === 200) {
              that.$message({
                message: '保存成功！',
                type: 'success',
              })
              // 关闭弹框
              that.closeFun(true)
            } else {
              that.$message({
                message: res.info,
                type: 'warning',
              })
            }
          })
        } else {
          return false
        }
      })
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    selectType(selVal) {
      if (selVal == 1) {
        this.fileInput = false
      } else {
        this.fileInput = true
      }
    },
  },
}
</script>
